package com.tencent.wxpay.demo.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxpay.demo.model.AccessToken;
import com.tencent.wxpay.demo.model.JSTicket;
import com.tencent.wxpay.demo.model.WeixinOauth2Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 公众平台通用接口工具类
 * @author Cheney
 *
 */
public class WeixinUtil {

	private static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl,
										 String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

//			if ("GET".equalsIgnoreCase(requestMethod))
//				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (ConnectException ce) {
			ce.printStackTrace();
			System.out.println("Weixin server connection timed out.");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("https request error:{}");
		}
		return jsonObject;
	}

	// 获取access_token的接口地址（GET） 限2000（次/天）, 测试号200次/天
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	/**
	 * 获取access_token
	 * @param appid 凭证
	 * @param appsecret 密钥
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appid).replace(
				"APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		System.out.println(jsonObject.toString());
		// 如果请求成功
		if (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
			} catch (JSONException e) {
				accessToken = null;
				// 获取token失败 , jsonObject.getInt("errcode"),
				// jsonObject.getString("errmsg")
				logger.error("获取token失败。" + jsonObject.toJSONString());
				System.out.printf("获取token失败 errcode:{%s} errmsg:{%s}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}
	
    // 获取 jsapi_ticket，为jsapi的签名使用
	private static final String JSTICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	/**
	 * 获取js_ticket,为jsapi签名所用
	 * @param accessToken
	 * @return
	 */
 	public static JSTicket getJsTicket(String accessToken) {
 		JSTicket jsticket = null;
 		String requestUrl = JSTICKET_URL.replace("ACCESS_TOKEN",
 				accessToken);
 		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
 		System.out.println(jsonObject.toString());
 		// 如果请求成功
 		if (null != jsonObject) {
 			try {
 				jsticket = new JSTicket();
 				jsticket.setTicket(jsonObject.getString("ticket"));
 				jsticket.setExpiresIn(jsonObject.getIntValue("expires_in"));
 			} catch (JSONException e) {
				jsticket = null;
				logger.error("获取ticket失败。" + jsonObject.toJSONString());
 				System.out.printf("获取ticket失败 errcode:{%s} errmsg:{%s}",jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
 			}
 		}
 		return jsticket;
 	}
    

	// 网页授权获取accesstoken接口url
	private static final String GET_OAUTH2_ACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	/**
	 * 获取网页授权凭证
	 *
	 * @param appId 公众账号的唯一标识
	 * @param appSecret 公众账号的密钥
	 * @param code
	 * @return WeixinAouth2Token
	 */
	public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
		WeixinOauth2Token weixinOauth2Token = null;
		// 拼接请求地址
		String requestUrl = GET_OAUTH2_ACCESSTOKEN_URL.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
		// 获取网页授权凭证
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			weixinOauth2Token = new WeixinOauth2Token();
			try {
				weixinOauth2Token.setAccessToken(jsonObject.getString("access_token"));
				weixinOauth2Token.setExpiresIn(jsonObject.getIntValue("expires_in"));
				weixinOauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
				weixinOauth2Token.setOpenId(jsonObject.getString("openid"));
				weixinOauth2Token.setScope(jsonObject.getString("scope"));
			} catch (Exception e) {
				weixinOauth2Token = null;
				System.out.println(jsonObject.toString());
				int errorCode = jsonObject.getIntValue("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				logger.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return weixinOauth2Token;
	}

	// 刷新网页授权凭证接口
	public static final String REFRESH_OAUTH2_ACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";

	/**
	 * 刷新网页授权凭证
	 *
	 * @param appId 公众账号的唯一标识
	 * @param refreshToken
	 * @return WeixinAouth2Token
	 */
	public static WeixinOauth2Token refreshOauth2AccessToken(String appId, String refreshToken) {
		WeixinOauth2Token weixinOauth2Token = null;
		// 拼接请求地址
		String requestUrl = REFRESH_OAUTH2_ACCESSTOKEN_URL.replace("APPID", appId).replace("REFRESH_TOKEN", refreshToken);
		// 刷新网页授权凭证
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			weixinOauth2Token = new WeixinOauth2Token();
			try {
				weixinOauth2Token.setAccessToken(jsonObject.getString("access_token"));
				weixinOauth2Token.setExpiresIn(jsonObject.getIntValue("expires_in"));
				weixinOauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
				weixinOauth2Token.setOpenId(jsonObject.getString("openid"));
				weixinOauth2Token.setScope(jsonObject.getString("scope"));
			} catch (Exception e) {
				weixinOauth2Token = null;
				System.out.println(jsonObject.toString());
				int errorCode = jsonObject.getIntValue("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				logger.error("刷新网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return weixinOauth2Token;
	}

	public static final String GET_SNS_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

 	/**
	 * URL编码（utf-8）
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
}